package com.link.play.fit.ai.ui.main.foodDatabase

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.view.children
import androidx.core.view.postDelayed
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.request.transition.ViewPropertyTransition
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.FoodInfoBean
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.bean.toRecentlyEatenData
import com.link.play.fit.ai.databinding.AcFoodDatabaseBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.ui.dialog.FoodDatabaseDialog
import com.link.play.fit.ai.ui.main.GlobalViewModel
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.adapter.FoodDatabaseAcAdapter
import com.link.play.fit.ai.utils.DateEx
import com.link.play.fit.ai.utils.EventUtils
import kotlinx.coroutines.launch
import java.util.Date

class FoodDatabaseAc : BaseActivity<AcFoodDatabaseBinding>(AcFoodDatabaseBinding::inflate) {

    companion object {
        const val AiFood = "AiFood"
    }

    private var adapter = FoodDatabaseAcAdapter()
    private val viewModel: FoodDatabaseViewModel by lazy {
        ViewModelProvider(this)[FoodDatabaseViewModel::class.java]
    }
    private val baseViewModel: GlobalViewModel by lazy {
        GlobalViewModel.getInstance(application)
    }

    var loadingFlag: Boolean = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initData()
    }

    fun initView() {
        binding.ivReturn.setOnClickListener {
            finish()
        }
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(
                s: CharSequence?,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (s == null || s.isEmpty()) {
                    switchEditAndAI(false)
                } else {
                    switchEditAndAI(true)
                }
                loadAnim(true)
                viewModel.getFoodList(s.toString())
            }

        })
        binding.rlEditFood.setOnClickListener {
            goToAc(LogFoodAc::class.java)
        }
        binding.rlAiFood.setOnClickListener {
//            val t = binding.etSearch.text
//            if (!TextUtils.isEmpty(t)) {
//                viewModel.getAiFood(t.toString())
//            }
            goToAc(MainAc::class.java) {
                putExtra(AiFood, binding.etSearch.text.toString())
                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
        }
        binding.recyclerSearch.layoutManager = LinearLayoutManager(this)
        binding.recyclerSearch.adapter = adapter
        //打开食物编辑
        adapter.openEditFood = { bean ->
            goToAc(FoodEditAc::class.java) {
                putExtra(FoodEditAc.Bean, bean)
                putExtra(FoodEditAc.IntentParamsSearch, true)
            }
        }
        //添加食物
        adapter.addFood = { str ->
            addRecentlyList(str)
//            CloudStore.addToList(
//                CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
//                CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
//                System.currentTimeMillis().toString(),
//                str.apply { select = false }
//            )
            val red = str.ingredients.first().apply {
                timeMillisencond = System.currentTimeMillis().toString()
            }.toRecentlyEatenData()
            CloudStore.addToList(
                CloudStore.DOC_RECENTLY_LIST_DATA,
                DateEx.getDayOfMonth(),
                red.createTime,
                red
            )
            EventUtils.event("food_database_add")
            baseViewModel.addRecentlyData(red)

            val dialog = FoodDatabaseDialog {
                goToAc(FoodEditAc::class.java) {
                    putExtra(FoodEditAc.Bean, str)
                    putExtra(FoodEditAc.IntentParamsSearch, true)
                }
            }.apply {
                build(this@FoodDatabaseAc)
                show()
            }
            binding.root.postDelayed(3000) {
                dialog.dismiss()
            }
        }
    }

    //获取数据
    fun initData() {
        lifecycleScope.launch {
            viewModel.foodInfoBean.collect {
                setRecycleData(true)
            }
        }
        lifecycleScope.launch {
            viewModel.foodInfoAi.collect {
                val food = it.foodInfo?.firstOrNull()
                if (food != null) {
                    addRecentlyList(food)
                    val red = food.ingredients.first().apply {
                        timeMillisencond = System.currentTimeMillis().toString()
                    }.toRecentlyEatenData()
                    CloudStore.addToList(
                        CloudStore.DOC_RECENTLY_LIST_DATA,
                        DateEx.getDayOfMonth(),
                        red.createTime,
                        red
                    )
                    baseViewModel.addRecentlyData(red)
                    finish()
                }
            }
        }
        setRecycleData(false)
    }

    // 设置列表里的数据
    fun setRecycleData(f: Boolean) = if (f) {
        //搜索到的数据
        binding.tvSearchTitle.text = resources.getString(R.string.suggestions)
        loadAnim(false)
        adapter.setData(viewModel.foodInfoBean.value.foodInfo)
    } else {
        binding.tvSearchTitle.text = resources.getString(R.string.recently_logged)
        loadingFlag = false
        //获取最近添加到首页的食物
        lifecycleScope.launch {
            var recentlyData =
                CloudStore.getList<FoodInfoBean>(
                    CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
                    CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
                )?.toMutableList() ?: mutableListOf()
//            recentlyData?.removeIf { if (it.type != 4 || TextUtils.isEmpty(it.ingredients)) true else false }
            recentlyData.reverse()
            if (recentlyData.isEmpty()) {
                binding.tvSearchTitle.text = resources.getString(R.string.suggestions)
                recentlyData = build(this@FoodDatabaseAc)
                recentlyData.forEach {
                    it.ingredients.first().timeMillisencond = ""
                }
            }
            runCatching {
                recentlyData.forEach {
                    it.ingredients.first().timeMillisencond = ""
                }
            }
            adapter.setData(recentlyData)
        }
    }

    //切换按钮的功能
    fun switchEditAndAI(flag: Boolean) = if (flag) {
        binding.rlAiFood.visibility = View.VISIBLE
        binding.rlEditFood.visibility = View.GONE
    } else {
        binding.rlEditFood.visibility = View.VISIBLE
        binding.rlAiFood.visibility = View.GONE
    }

    //添加到最近添加的食物列表,和首页的数据分开
    fun addRecentlyList(str: FoodInfoBean) {
        CloudStore.addToList(
            CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
            CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
            System.currentTimeMillis().toString(),
            str.apply { select = false }
        )
    }

    //true 打开动画 false 关闭动画
    fun loadAnim(f: Boolean) {
        if (f) {

        } else {
            binding.clPlaceholder.showOriginal()
            binding.clPlaceholder.visibility = View.GONE
            binding.tvSearchTitle.visibility = View.VISIBLE
            return
        }
        if (!loadingFlag) {
            loadingFlag = true
        } else {
            return
        }
        adapter.clear()
        binding.clPlaceholder.visibility = View.VISIBLE
        binding.tvSearchTitle.visibility = View.INVISIBLE
        binding.clPlaceholder.showSkeleton()
    }
}